package com.paw.ruoyi.admin.controller.system;

import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.extra.servlet.ServletUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.paw.ruoyi.admin.common.annotion.OperatorLog;
import com.paw.ruoyi.admin.common.annotion.RequiresPermissions;
import com.paw.ruoyi.admin.common.constant.BusinessType;
import com.paw.ruoyi.admin.common.constant.CommonConstant;
import com.paw.ruoyi.admin.common.constant.UserConstants;
import com.paw.ruoyi.admin.common.context.UserContext;
import com.paw.ruoyi.admin.common.context.UserContextHolder;
import com.paw.ruoyi.admin.common.annotion.SkipLogParam;
import com.paw.ruoyi.admin.common.annotion.SkipResponseLog;
import com.paw.ruoyi.admin.biz.service.SysPermissionService;
import com.paw.ruoyi.admin.biz.service.TokenService;
import com.paw.ruoyi.admin.common.AjaxResult;
import com.paw.ruoyi.admin.common.domain.PageDomain;
import com.paw.ruoyi.admin.common.TableDataInfo;
import com.paw.ruoyi.admin.core.util.TableSupport;
import com.paw.ruoyi.admin.controller.BaseController;
import com.paw.ruoyi.admin.domain.SysRole;
import com.paw.ruoyi.admin.domain.SysUser;
import com.paw.ruoyi.admin.domain.SysUserRole;
import com.paw.ruoyi.admin.service.ISysRoleService;
import com.paw.ruoyi.admin.service.ISysUserService;
import com.paw.ruoyi.admin.utils.ExcelUtil;
import com.paw.ruoyi.admin.core.util.ServletUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 角色信息
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/api/system/role")
public class SysRoleController extends BaseController {

  @Autowired
  private ISysRoleService roleService;

  @Autowired
  private TokenService tokenService;

  @Autowired
  private SysPermissionService permissionService;

  @Autowired
  private ISysUserService userService;

  @RequiresPermissions("system:role:list")
  @GetMapping("/list")
  public TableDataInfo list (SysRole role) {
    PageDomain pageDomain = TableSupport.buildPageRequest();
    Page<SysRole> pageParam = new Page<>(pageDomain.getPageNum(), pageDomain.getPageSize());
    IPage<SysRole> page = roleService.selectRolePageList(pageParam, role);
    return getDataTable(page);
  }


  @SkipLogParam
  @SkipResponseLog
  @OperatorLog(title = "角色管理", businessType = BusinessType.EXPORT)
  @RequiresPermissions("system:role:export")
  @PostMapping("/export")
  public void export (HttpServletResponse response, SysRole role) {
    List<SysRole> list = roleService.selectRoleList(role);
    ExcelUtil<SysRole> util = new ExcelUtil<SysRole>(SysRole.class);
    util.exportExcel(response, list, "角色数据");
  }

  /**
   * 根据角色编号获取详细信息
   */
  @RequiresPermissions("system:role:query")
  @GetMapping(value = "/{roleId}")
  public AjaxResult getInfo (@PathVariable Long roleId) {
    roleService.checkRoleDataScope(roleId);
    return AjaxResult.success(roleService.selectRoleById(roleId));
  }

  /**
   * 新增角色
   */
  @RequiresPermissions("system:role:add")
  @OperatorLog(title = "角色管理", businessType = BusinessType.INSERT)
  @PostMapping
  public AjaxResult add (@Validated @RequestBody SysRole role) {
    if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleNameUnique(role))) {
      return AjaxResult.error("新增角色'" + role.getRoleName() + "'失败，角色名称已存在");
    } else if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleKeyUnique(role))) {
      return AjaxResult.error("新增角色'" + role.getRoleName() + "'失败，角色权限已存在");
    }
    role.setCreateBy(getUsername());
    return toAjax(roleService.insertRole(role));

  }

  /**
   * 修改保存角色
   */
  @RequiresPermissions("system:role:edit")
  @OperatorLog(title = "角色管理", businessType = BusinessType.UPDATE)
  @PutMapping
  public AjaxResult edit (@Validated @RequestBody SysRole role) {
    roleService.checkRoleAllowed(role);
    if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleNameUnique(role))) {
      return AjaxResult.error("修改角色'" + role.getRoleName() + "'失败，角色名称已存在");
    } else if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleKeyUnique(role))) {
      return AjaxResult.error("修改角色'" + role.getRoleName() + "'失败，角色权限已存在");
    }
    role.setUpdateBy(getUsername());

    if (roleService.updateRole(role) > 0) {
      // 更新缓存用户权限
      Long userId = UserContextHolder.getUserId();
      if (userId != null && userId != 1L) {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        Set<String> permissions = permissionService.getMenuPermission(sysUser);
        UserContext userContext = UserContextHolder.getUser();
        userContext.setPermissions(permissions);
        String token = ServletUtil.getHeader(ServletUtils.getRequest(), CommonConstant.TOKEN, CharsetUtil.UTF_8);
        tokenService.updateCacheUserContext(token, userContext);
      }
      return AjaxResult.success();
    }
    return AjaxResult.error("修改角色'" + role.getRoleName() + "'失败，请联系管理员");
  }

  /**
   * 修改保存数据权限
   */
  @RequiresPermissions("system:role:edit")
  @OperatorLog(title = "角色管理", businessType = BusinessType.UPDATE)
  @PutMapping("/dataScope")
  public AjaxResult dataScope (@RequestBody SysRole role) {
    roleService.checkRoleAllowed(role);
    return toAjax(roleService.authDataScope(role));
  }

  /**
   * 状态修改
   */
  @RequiresPermissions("system:role:edit")
  @OperatorLog(title = "角色管理", businessType = BusinessType.UPDATE)
  @PutMapping("/changeStatus")
  public AjaxResult changeStatus (@RequestBody SysRole role) {
    roleService.checkRoleAllowed(role);
    role.setUpdateBy(getUsername());
    return toAjax(roleService.updateRoleStatus(role));
  }

  /**
   * 删除角色
   */
  @RequiresPermissions("system:role:remove")
  @OperatorLog(title = "角色管理", businessType = BusinessType.DELETE)
  @DeleteMapping("/{roleIds}")
  public AjaxResult remove (@PathVariable Long[] roleIds) {
    return toAjax(roleService.deleteRoleByIds(roleIds));
  }

  /**
   * 获取角色选择框列表
   */
  @RequiresPermissions("system:role:query")
  @GetMapping("/optionselect")
  public AjaxResult optionselect () {
    return AjaxResult.success(roleService.selectRoleAll());
  }

  /**
   * 查询已分配用户角色列表
   */
  @RequiresPermissions("system:role:list")
  @GetMapping("/authUser/allocatedList")
  public TableDataInfo allocatedList (SysUser user) {
    PageDomain pageDomain = TableSupport.buildPageRequest();
    Page<SysUser> pageParam = new Page<>(pageDomain.getPageNum(), pageDomain.getPageSize());
    Page<SysUser> page = userService.selectAllocatedPageList(pageParam, user);
    return getDataTable(page);
  }

  /**
   * 查询未分配用户角色列表
   */
  @RequiresPermissions("system:role:list")
  @GetMapping("/authUser/unallocatedList")
  public TableDataInfo unallocatedList (SysUser user) {
    PageDomain pageDomain = TableSupport.buildPageRequest();
    Page<SysUser> pageParam = new Page<>(pageDomain.getPageNum(), pageDomain.getPageSize());
    Page<SysUser> page = userService.selectUnallocatedPageList(pageParam, user);
    return getDataTable(page);
  }

  /**
   * 取消授权用户
   */
  @RequiresPermissions("system:role:edit")
  @OperatorLog(title = "角色管理", businessType = BusinessType.GRANT)
  @PutMapping("/authUser/cancel")
  public AjaxResult cancelAuthUser (@RequestBody SysUserRole userRole) {
    return toAjax(roleService.deleteAuthUser(userRole));
  }

  /**
   * 批量取消授权用户
   */
  @RequiresPermissions("system:role:edit")
  @OperatorLog(title = "角色管理", businessType = BusinessType.GRANT)
  @PutMapping("/authUser/cancelAll")
  public AjaxResult cancelAuthUserAll (Long roleId, Long[] userIds) {
    return toAjax(roleService.deleteAuthUsers(roleId, userIds));
  }

  /**
   * 批量选择用户授权
   */
  @RequiresPermissions("system:role:edit")
  @OperatorLog(title = "角色管理", businessType = BusinessType.GRANT)
  @PutMapping("/authUser/selectAll")
  public AjaxResult selectAuthUserAll (Long roleId, Long[] userIds) {
    return toAjax(roleService.insertAuthUsers(roleId, userIds));
  }
}
